<?php
require_once("Database.php");

class BaseDAO
{
    private $database;

    public function __construct()
    {
        $this->database = Database::getInstance();
    }

    protected function getItem($table, $id)
    {
        return $this->executeQuery("SELECT * FROM $table WHERE Id = '$id'");
    }

    protected function addItem($table, $item)
    {
        $fields = array_keys($item);
        $values = $this->escapeValues(array_values($item));
        $sql = $this->getBaseInsertStatement($table, $fields);
        $sql .= "(" . join(", ", $values) . ")";
        return $this->executeQuery($sql);
    }

    protected function updateItem($table, $item, $itemId)
    {
        $sql = $this->getBaseUpdateStatement($table, $item, $itemId);
        echo $sql . "\n" . "</br>";
        return $this->executeQuery($sql);
    }

    protected function getInsertedItemId()
    {
        return mysqli_insert_id($this->getConnection());
    }

    protected function deleteItem($table, $id)
    {
        return $this->executeQuery("DELETE FROM $table WHERE Id = '$id'");
    }

    protected function deleteItemWhere($table, $fieldsMap)
    {
        $where = array();
        foreach ($fieldsMap as $key => $value) {
            $where[] = "`" . $key . "` = " . $this->escapeValue($value);
        }

        return $this->executeQuery("DELETE FROM $table WHERE ".join(" AND ", $where));
    }

    protected function executeQuery($query)
    {
        return $this->database->executeQuery($query);
    }

    protected function executeQueryWithConnection($connection, $query)
    {
        return $this->database->executeQueryWithConnection($connection, $query);
    }

    protected function getBaseInsertStatement($table, $fields)
    {
        return "INSERT INTO `" . $table . "` (`" . join('`, `', $fields) . "`) VALUES ";
    }

    public function escapeString($value)
    {
        return mysqli_real_escape_string($this->getConnection(), $value);
    }

    private function getConnection()
    {
        return $this->database->getConnection();
    }

    protected function escapeValues($values)
    {
        $escapedValues = array();
        foreach ($values as $value) {
            $escapedValues[] = $this->escapeValue($value);
        }
        return $escapedValues;
    }

    protected function escapeValue($value)
    {
        return $value === NULL ? 'NULL' : "'" . $this->escapeString(trim($value)) . "'";
    }

    private function getBaseUpdateStatement($table, $fieldsMap, $itemId)
    {
        $itemValues = array();
        foreach ($fieldsMap as $key => $value) {
            $itemValues[] = "`" . $key . "` = " . $this->escapeValue($value);
        }
        return "UPDATE `$table` SET ".join(", ", $itemValues) . " WHERE Id = $itemId";
    }
} 